package utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 冷丶 on 2017/11/19.
 */
@WebServlet(name = "DispapcherServlet",urlPatterns = "/")
public class DispapcherServlet extends HttpServlet {
    Map<String,Method> urlMap = new HashMap<String, Method>();
    Map<Method,Object> methodMap = new HashMap();
    @Override
    public void init() throws ServletException {
        String packName = "controller";
        try {
            List<Class> classes = ControllerUtils.getAllClass(packName);
            for (Class c:classes){
                Method[] methods = c.getMethods();
                for (Method m : methods){
                    URLMapping annotation = m.getAnnotation(URLMapping.class);
                    if (annotation != null){
                        String url = annotation.url();
                        urlMap.put(url,m);
                        Object o = c.newInstance();
                        methodMap.put(m,o);
                    }
                }

            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = req.getServletPath();
        if (!urlMap.containsKey(url)){
            resp.setStatus(404);
            return;
        }
        Method m = urlMap.get(url);
        Object o = methodMap.get(m);

        try {
            if (req.getMethod().equals("POST")){
            req.setCharacterEncoding("utf-8");
        }
            String str = (String) m.invoke(o,req,resp);
            if (str!=null || (!"".equals(str))){
                if (str.startsWith("Redirect:")){
                    resp.sendRedirect(str.substring(9));
                }else {
                    req.getRequestDispatcher(str).forward(req,resp);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }



}
